<template>
    <div class="product-manager">
        <basic-container>
            <!--顶部搜索表单-->
            <div class="madp-product-management-search">
                <el-input placeholder="请输入姓名" @input="name = name.replace(/\s+/g, '')" v-model.trim="name"></el-input>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleClear">清空</el-button>
            </div>
            <div class="madp-synchronous-btn">
                <el-button type="primary" @click="handleAddProductManager">新增产品经理</el-button>
            </div>
            <!--table-->
            <div class="madp-product-content">
                <div class="madp-product-table">
                    <el-table :header-cell-style="{ background: 'rgb(255, 191, 191)', color: 'rgb(44,44,44)' }" stripe :data="productManagerData" v-loading="loadingList">
                        <el-table-column prop="id" align="center" label="编号" width="100"></el-table-column>
                        <el-table-column prop="employeeName" align="center" label="姓名"></el-table-column>
                        <el-table-column prop="userLevel" align="center" label="职级">
                            <template slot-scope="scope">{{ scope.row.userLevel | filterUserLevel }}</template>
                        </el-table-column>
                        <el-table-column prop="rangeName" align="center" label="权限"></el-table-column>
                        <el-table-column prop="phone" align="center" label="联系方式"></el-table-column>
                        <el-table-column prop="state" align="center" label="授权" width="100">
                            <template slot-scope="scope">
                                <el-switch v-model="scope.row.state" :active-value="2" :inactive-value="1" @change="handleChangeSelect(scope.row)"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="madp-table-page">
                        <el-pagination
                            background
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page.currentPage"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="page.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="page.total"
                            style="float: right"
                        ></el-pagination>
                    </div>
                </div>
            </div>
        </basic-container>
        <!-- 新增产品经理弹框 开始 -->
        <el-dialog :title="dialogTitle" :visible="dialogShow" :close-on-click-modal="false" :before-close="handleCancelDialog" append-to-body custom-class="dialog" width="50%">
            <div class="madp-dialog-content">
                <div style="margin-top: 20px">
                    <el-form ref="addProductManagerData" :model="addProductManagerData" :rules="productManagerRules" label-width="140px">
                        <el-form-item prop="wxUserId" label="选择成员:">
                            <el-select v-model="addProductManagerData.wxUserId" placeholder="请选择成员" @change="handleChangeMember" :disabled="isDisabledMember">
                                <el-option v-for="item in member" :key="item.id" :label="item.name" :value="item.wxUserId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="phone" label="联系方式:">
                            <el-input
                                v-model.trim="addProductManagerData.phone"
                                @input="addProductManagerData.phone = addProductManagerData.phone.replace(/\D/g, '')"
                                placeholder="回显手机号不可修改"
                                disabled
                            ></el-input>
                        </el-form-item>
                        <el-form-item prop="userLevel" label="职级:">
                            <el-select v-model="addProductManagerData.userLevel" placeholder="请选择职级">
                                <el-option v-for="item in rank" :key="item.userLevel" :label="item.name" :value="item.userLevel"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="permissionIdList" label="权限:">
                            <el-select
                                v-model="addProductManagerData.permissionIdList"
                                placeholder="请选择产品权限"
                                @focus="getProductPermissions"
                                :disabled="isDisabled"
                                multiple
                                :loading="permissionLoading"
                            >
                                <el-option v-for="item in permission" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="handleCancelDialog">取消</el-button>
                <el-button type="primary" :loading="btnLoading" @click="handleConfirm">确定</el-button>
            </div>
        </el-dialog>
        <!-- 新增产品经理弹框 结束 -->
    </div>
</template>

<script>
import { getProductManager, getMembers, getPermission, postProductManager, putProductManager, deleteProductManager, getProductManagerChange } from '@/api/product-manage/product-manager';
export default {
    name: 'product-manager',
    data() {
        return {
            name: '',
            productManagerData: [],
            loadingList: false,
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            dialogTitle: '',
            dialogShow: false,
            addProductManagerData: {
                wxUserId: '',
                phone: '',
                userLevel: undefined,
                permissionIdList: []
            },
            productManagerRules: {
                member: [{ required: true, message: '请选择成员', trigger: 'change' }],
                phone: [{ required: true, message: '联系方式', trigger: 'blur' }],
                level: [{ required: true, message: '请选择职级', trigger: 'change' }],
                permissionIdList: [
                    {
                        required: true,
                        message: '请选择产品权限',
                        trigger: 'change'
                    }
                ]
            },
            btnLoading: false,
            // 职级
            rank: [
                {
                    name: '初级产品经理',
                    userLevel: 1
                },
                {
                    name: '中级产品经理',
                    userLevel: 2
                },
                {
                    name: '高级产品经理',
                    userLevel: 3
                }
            ],
            // 成员
            member: [],
            // 权限
            permission: [],
            addFormData: {
                employeeId: '',
                employeeName: '',
                phone: '',
                userLevel: undefined,
                prodRange: '',
                rangeName: '',
                deptId: undefined
            },
            deptId: undefined,
            isDisabledMember: false,
            isDisabled: true,
            permissionLoading: false,
            id: undefined
        };
    },
    filters: {
        filterUserLevel(val) {
            switch (val) {
                case 1:
                    return '初级产品经理';
                case 2:
                    return '中级产品经理';
                case 3:
                    return '高级产品经理';
            }
        }
    },
    mounted() {
        this.getList(this.page);
    },
    methods: {
        // 查询成员列表
        getMemberList() {
            getMembers({})
                .then((res) => {
                    if (res.data.code === 0) {
                        this.member = res.data.data;
                    }
                })
                .catch(() => {});
        },
        // 查询权限列表
        getProductPermissions() {
            this.permissionLoading = true;
            getPermission({ id: this.deptId })
                .then((res) => {
                    if (res.data.code === 0) {
                        this.permission = res.data.data;
                    }
                    this.permissionLoading = false;
                })
                .catch(() => {
                    this.permissionLoading = false;
                });
        },
        // 分页查询list
        getList(page, params) {
            this.loadingList = true;
            let obj = Object.assign({ current: page.currentPage, size: page.pageSize }, { ...params });
            getProductManager(obj)
                .then((res) => {
                    if (res.data.code === 0) {
                        this.productManagerData = res.data.data.records;
                        this.page.total = res.data.data.total;
                    }
                    this.loadingList = false;
                })
                .catch(() => {
                    this.loadingList = false;
                });
        },
        // 搜索
        handleSearch() {
            this.getList(this.page, { name: this.name });
        },
        // 清空
        handleClear() {
            this.name = '';
            this.getList(this.page);
        },
        // 新增产品经理btn
        handleAddProductManager() {
            this.dialogTitle = '新增产品经理';
            this.isDisabledMember = false;
            // 获取成员列表
            this.getMemberList();
            this.dialogShow = true;
        },
        // 选择成员
        handleChangeMember(id) {
            let member = this.member.filter((item) => item.wxUserId === id);
            let { deptId, mobile, name, wxUserId } = member[0];
            this.deptId = deptId;
            this.addProductManagerData.phone = mobile;
            this.addFormData.employeeId = wxUserId;
            this.addFormData.employeeName = name;
            this.addFormData.phone = mobile;
            this.isDisabled = false;
        },
        // 授权按钮
        handleChangeSelect(data) {
            let state = data.state === 1 ? 1 : 2;
            getProductManagerChange({ id: data.id, state: state })
                .then((res) => {
                    if (res.data.code === 0) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        });
                        this.getList(this.page);
                    }
                })
                .catch(() => {});
        },
        // 表格编辑
        handleEdit(data) {
            this.getMemberList();
            this.dialogTitle = '编辑产品经理';
            this.dialogShow = true;
            this.isDisabledMember = true;
            this.$nextTick(() => {
                let obj = JSON.parse(JSON.stringify(data));
                this.id = obj.id; // 此id为数据修改提交时使用
                this.deptId = obj.deptId;
                this.addProductManagerData.userLevel = obj.userLevel;
                this.addProductManagerData.wxUserId = obj.employeeId;
                this.addProductManagerData.phone = obj.phone;
                this.isDisabled = false;
                this.addFormData.employeeId = obj.employeeId;
                this.addFormData.employeeName = obj.employeeName;
                this.addFormData.phone = obj.phone;
                this.getProductPermissions();
                console.log(obj);
                this.addProductManagerData.permissionIdList = obj.range.map(Number);
            });
        },
        // 表格删除
        handleDelete(data) {
            this.$confirm('是否确认删除该产品经理?', '温馨提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            })
                .then(() => {
                    deleteProductManager({ id: data.id })
                        .then((res) => {
                            if (res.data.code === 0) {
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg
                                });
                                this.getList(this.page);
                            }
                        })
                        .catch(() => {});
                })
                .catch(() => {});
        },
        /**
         * 分页-改变每页记录条数触发查询
         **/
        handleSizeChange(pageSize) {
            this.page.pageSize = pageSize;
            this.page.currentPage = 1;
            this.getList(this.page, { name: this.name });
        },
        /**
         * 分页-改变当前页码记录条数触发查询
         **/
        handleCurrentChange(currentPage) {
            this.page.currentPage = currentPage;
            this.getList(this.page, { name: this.name });
        },
        // 关闭弹框
        handleCancelDialog() {
            this.$refs.addProductManagerData.resetFields();
            this.dialogShow = false;
        },
        // 弹框确定
        handleConfirm() {
            let _this = this;
            this.$refs.addProductManagerData.validate((validate) => {
                if (validate) {
                    if (_this.dialogTitle === '新增产品经理') {
                        _this.btnLoading = true;
                        _this.addFormData.prodRange = _this.addProductManagerData.permissionIdList.toString();
                        _this.addFormData.deptId = _this.deptId;
                        _this.addFormData.rangeName = _this.getArrEqual(_this.permission, _this.addProductManagerData.permissionIdList);
                        _this.addFormData.userLevel = _this.addProductManagerData.userLevel;
                        postProductManager(this.addFormData)
                            .then((res) => {
                                if (res.data.code === 0) {
                                    _this.$message({
                                        type: 'success',
                                        message: res.data.msg
                                    });
                                }
                                _this.btnLoading = false;
                                _this.dialogShow = false;
                                _this.$refs.addProductManagerData.resetFields();
                                _this.getList(_this.page);
                            })
                            .catch((err) => {
                                _this.btnLoading = false;
                            });
                    } else if (_this.dialogTitle === '编辑产品经理') {
                        _this.btnLoading = true;
                        _this.addFormData.prodRange = _this.addProductManagerData.permissionIdList.toString();
                        _this.addFormData.deptId = _this.deptId;
                        _this.addFormData.rangeName = _this.getArrEqual(_this.permission, _this.addProductManagerData.permissionIdList);
                        _this.addFormData.userLevel = _this.addProductManagerData.userLevel;
                        _this.addFormData = Object.assign(_this.addFormData, {
                            id: _this.id
                        });
                        putProductManager(_this.addFormData)
                            .then((res) => {
                                if (res.data.code === 0) {
                                    _this.$message({
                                        type: 'success',
                                        message: res.data.msg
                                    });
                                }
                                _this.btnLoading = false;
                                _this.dialogShow = false;
                                _this.$refs.addProductManagerData.resetFields();
                                _this.getList(_this.page);
                            })
                            .catch((err) => {
                                _this.btnLoading = false;
                            });
                    }
                }
            });
        },
        // 过滤数据
        getArrEqual(arr1, arr2) {
            let newArr = [];
            for (let i = 0; i < arr1.length; i++) {
                for (let j = 0; j < arr2.length; j++) {
                    if (arr1[i].id === arr2[j]) {
                        newArr.push(arr1[i].name);
                    }
                }
            }
            return newArr.toString();
        }
    }
};
</script>

<style lang="scss" scoped>
.product-manager {
    .madp-product-management-search {
        display: flex;
        justify-content: flex-end;
        /deep/.el-input {
            margin-right: 10px;
            width: 200px;
        }

        .madp-item-btn {
            /deep/ .el-form-item__content {
                display: flex;
                margin-left: 0 !important;
            }
        }
    }
    .madp-product-content {
        margin-top: 10px;
    }
}
.madp-table-page {
    padding: 10px;
    display: flex;
    justify-content: flex-end;
}
.madp-dialog-content {
    .el-input,
    /deep/.el-select > .el-input {
        width: 300px;
    }
}
</style>
